package com.cq.hd.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cq.hd.common.entity.GaoDeGeocode;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class GaoDeUtils {

    private final static String HOST = "https://restapi.amap.com";

    private final static String GEOCODE_URL = "/v3/geocode/regeo";
    // 115a831bb459eafc34a53c3b81f8862a
    private final static String key = "bf826546e95be95b4911edef0d1348a6";

    public static GaoDeGeocode degreesToCity(String longitude, String latitude) {
        Map<String, String> headMap = new HashMap<>();

        Map<String, String> params = new HashMap<>();
        params.put("key", key);
        params.put("output", "json");
        params.put("location", longitude + "," + latitude);
        params.put("radius", "1000");
        params.put("extensions", "base");
        params.put("roadlevel", "0");

        try {
            HttpResponse response = HttpUtils.doPost(HOST, GEOCODE_URL, headMap, params, JSON.toJSONString(params));
            String resultStr = EntityUtils.toString(response.getEntity());
            log.info("GEOCODE_URL-result:{}", resultStr);
            JSONObject result = JSON.parseObject(resultStr);

            String status = result.getString("status");
            if ("1".equals(status)) {
                JSONObject regeocode = result.getJSONObject("regeocode");
                if (regeocode != null) {
                    String formattedAddress = regeocode.getString("formatted_address");
                    JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
                    if (addressComponent != null) {
                        String country = addressComponent.getString("country");
                        String province = addressComponent.getString("province");
                        String city = addressComponent.getString("city");
                        String district = addressComponent.getString("district");
                        String township = addressComponent.getString("township");

                        GaoDeGeocode gaoDeGeocode = new GaoDeGeocode();
                        gaoDeGeocode.setFormattedAddress(formattedAddress);
                        gaoDeGeocode.setCountry(country);
                        gaoDeGeocode.setProvince(province);
                        gaoDeGeocode.setCity(city);
                        gaoDeGeocode.setCountyName(district);
                        gaoDeGeocode.setTownship(township);

                        return gaoDeGeocode;
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取地理位置异常", e);
        }

        return null;
    }

}
